#include <stdlib.h>
#include <iostream>
#include <fstream>
#include <iomanip>

using namespace std;

int main(int argc,char *argv[])
{
    if(argc!=5) {
				cout << "error: invalid number of arguments\n\n"
						 << "usage: " << argv[0] << " size columns infile outfile\n\n" ;
				exit(1);
    }

    int bufsize=atoi(argv[1]);
    if(bufsize<=0) {
				cout << "error: invalid buffer size: " << bufsize << "\n\n";
				exit(1);
    }
    cout << "size: " << bufsize << endl;

    int columns=atoi(argv[2]);
    if(columns<=0) {
				cout << "error: invalid number of columns: " << columns << "\n\n";
				exit(1);
    }
    cout << "columns: " << columns << endl;

		ifstream in(argv[3]);
		if(!in) {
				cout << "error: could not open input file \""
						 << argv[3] << "\"\n\n";
				exit(1);
		}

		ofstream out(argv[4]);
		if(!out) {
				cout << "error: could not open out file \"" << argv[4] << "\"\n\n";
				exit(1);
		}

    unsigned int *buf = new unsigned int[columns*bufsize];
    if(!buf) {
	cout << "error: could not allocate memory\n\n";
	exit(1);
    }

    cout << "clear buffer" << endl;
    for(int i=0; i<columns*bufsize; i++) buf[i]=0;

    cout << "doing histogramm..." << flush;
    int line=0;
    while(!in.eof()) {
	int d;
	for(int c=0; c<columns; c++) {
	    in >> d;
	    if(in.rdstate() != ios::goodbit) {
		if(in.eof()) break; //ok end of file
		cout << "read error\n\n"; exit(1);
	    } else {
		if(d<0) {
		    cout << "error: d = " << d << " < 0 " << endl << endl;
		    exit(1);
		}
		if(d>=bufsize) {
		    cout << "error: d = " << d << " >= bufsize = " << bufsize
			 << " line: " << line << " column: " << c
			 << endl << endl;
		    //exit(1);
		} else {
		    cerr  << d; if(c < (columns-1)) cerr << " ";
		    buf[ c * bufsize + d ]++;
		}
	    }
	}
	line++;
	cerr << "\n";
    }
    cout << "finished" << endl;

    for(int i=0; i<bufsize; i++) {
//	out << i << " ";
	for(int c=0; c<columns; c++)
	    out << buf[ c*bufsize + i ] << " ";
	out << endl;
    }

    in.close();
    out.close();
}
